<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\fetch\kuaishou;

use app\enum\CommonEnum;
use app\enum\ConfigEnum;
use app\enum\KuaiShouEnum;
use app\model\ClientAccountModel;
use app\model\KsUserVideoKeyFrameModel;
use app\model\KsUserVideoModel;
use app\service\client\AccountService;
use app\service\fetch\MediaInterface;
use app\service\fetch\MediaService;
use app\service\kuaishou\MaterialService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;

final class VideoKeyFrameService extends MediaService implements MediaInterface
{
//    /**
//     * @var string 数据拉取key
//     */
//    protected const FETCH_KEY = ConfigEnum::CACHE_CONFIG[KuaiShouEnum::LIST_CONFIG_LOCK_KEY]['video_key_frame'];

    /**
     * 获取视频推荐封面.
     *
     * @param string $advertiserId 账户id
     */
    public static function getVideoKeyFrame(string $advertiserId = ''): bool
    {
        try {
            // 获取账户信息
            $obj = AccountService::getAccountModel(0, $advertiserId);
            if (! $obj instanceof ClientAccountModel || ! $obj->getKey()) {
                return self::setError('账户数据不存在');
            }
            // 获取user-id
            $userId = AccountService::getKsUserId($advertiserId);
            if (! $userId) {
                return self::setError('获取user_id失败');
            }
            $photoIds = self::getKsUserPhotoIds($userId);
            if (! $photoIds) {
                return true;
            }
            foreach ($photoIds as $photoId) {
                $result = self::getList($advertiserId, $photoId);
                if ($result === false) {
                    return false;
                }
                if (count($result['data']) == 0) {
                    break;
                }
                foreach ($result['data'] as $item) {
                    $model = self::getInfo($photoId, $item);
                    if (! $model instanceof KsUserVideoKeyFrameModel || ! $model->getKey()) {
                        $model = new KsUserVideoKeyFrameModel();
                    }
                    $model->setAttrs([
                        'photo_id' => $photoId,
                        'key_frame_url' => $item,
                    ]);
                    if (! $model->save()) {
                        throw new \Exception('保存数据出错');
                    }
                }
            }
            return true;
        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }

    /**
     * 获取可选的推荐封面列表.
     *
     * @param string $advertiserId 账户id
     * @param string $photoId 视频id
     * @return bool|mixed|string
     */
    private static function getList(string $advertiserId = '', string $photoId = '')
    {
        $token = AccountService::getToken(CommonEnum::KS_MEDIA, $advertiserId);
        if (! $token) {
            return self::setError('token获取失败');
        }
        $headers = [
            'Access-Token' => $token,
            'Content-Type' => 'application/json',
        ];
        $params = [
            'advertiser_id' => $advertiserId,
            'photo_ids' => [$photoId],
        ];
        return MaterialService::getVideoKeyFrame($headers, $params);
    }

    /**
     * 获取视频信息.
     * @param string $photoId 视频id
     * @param string $keyFrameUrl 推荐封面地址
     * @return null|array|KsUserVideoModel|mixed|Model
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private static function getInfo(string $photoId = '', string $keyFrameUrl = '')
    {
        $where = [
            ['photo_id', '=', $photoId],
            ['key_frame_url', '=', $keyFrameUrl],
        ];
        return (new KsUserVideoKeyFrameModel())->where($where)->field(true)->find();
    }

    /**
     * 获取user-id下视频.
     * @param string $userId user-id
     * @return array|KsUserVideoModel[]
     */
    private static function getKsUserPhotoIds(string $userId = ''): array
    {
        return (new KsUserVideoModel())->where('user_id', $userId)
            ->where('new_status', 1)
            ->where('outer_loop_native', [0, 2])
            ->column('photo_id');
    }
}
